<?php
/**
 * Html class
 * Utilities to create HTML elements
 */
namespace PUF;

class Html {
	protected $webroot = '';
	
	public function __construct() {
		$this->webroot = Router::getInstance()->getWebroot();
	}
	
	public function getWebroot() {
		return $this->webroot;
	}
	
	public function link($text, $route, $options = []) {
		$textOptions = '';
		foreach ($options as $key => $option) {
			$textOptions .= $key . '="' . $option . '" ';
		}
		
		if (is_object($route)) {
			$route = $route->getUrl();
		}
		
		if ($this->isRelativeUrl($route)) {
			$route = $this->webroot . $route;
		}
		
		$link = '<a href="' . $route . '" ' . $textOptions . '>' . $text . '</a>';
		
		return $link;
	}
	
	public function img($imgName, $options = []) {
		$textOptions = '';
		foreach ($options as $key => $option) {
			$textOptions .= $key . '="' . $option . '" ';
		}
		
		if ($this->isRelativeUrl($imgName)) {
			$imgName = $this->webroot . 'img/' . $imgName;
		}
		
		$img = '<img src="' . $imgName . '" ' . $textOptions . '>';
				
		return $img;
	}
	
	protected function isRelativeUrl($url) {
		return substr($url, 0, 4) != 'http'
				&& substr($url, 0, 3) != 'ftp'
				&& substr($url, 0, 6) != 'mailto';
	}
}